import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import *as todoActions from '../store/actions/todo.actions'
import { getIn } from "immutable"

class Main extends Component {

  componentDidMount(){
	this.props.load_todo()
  }

  deleteList(id){
	if (window.confirm('请确认是否删除')){
		this.props.remove_todo(id)
		// console.log(id)
	}
  }

	changeState(id, env){
		this.props.modify_todo({id, isCompleted: env.target.checked })
	}

	modifyName(id,env){
		this.props.edit_todo({id: id, isEditing: false})
		this.props.modify_todo_name({id: id, taskName: env.target.value})
	}
  render() {
		// console.log(this.props)
    return (
      <section className="main"> 
				<input className="toggle-all" type="checkbox" />
				<ul className="todo-list">
					{
						this.props.todos.map(item => {
							let classes = []
							if (item.isCompleted){classes.push('completed')}
							if (item.isEditing) {classes.push('editing')}
								return (
									<li key={item.id} className={classes.join('')}>
					    	<div className="view">
					    		<input className="toggle" type="checkbox" defaultChecked={item.isCompleted}
									onChange={this.changeState.bind(this, item.id)}/>
					    		<label onDoubleClick={() => { this.props.edit_todo({id: item.id, isEditing: true }) }}>{item.taskName}</label>
					    		<button className="destroy" onClick={this.deleteList.bind(this, item.id)}></button>
					    	</div>
					    	<input className="edit" defaultValue={item.taskName} onBlur={ this.modifyName.bind(this, item.id)} />
					    </li>
								)
							}
						)
					}	
				</ul>
			</section>
    )
  }
}
function todoFilter(todos, filter){
	switch (filter){
		case 'all':
			return todos
		case 'active':
			return todos.filter(todo => !todo.isCompleted)
		case 'completed':
			return todos.filter(todo => todo.isCompleted)
		default :
		return todos
	}
}
// 获取store中的数据
const mapStateToProps = (state) => ({
	todos: todoFilter(getIn(state.todoReducer, ['todos']), getIn(state.todoReducer,['filter']))
	// state getIn
})
// 处理store中的数据  触发dispatch函数
const mapDispatchToProps = (dispatch) => ({
	...bindActionCreators(todoActions, dispatch)
})


export default connect(mapStateToProps, mapDispatchToProps)(Main)
